package com.yzc.interceptor;

import com.yzc.util.JwtUtil;
import feign.RequestInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

@Component
@RequiredArgsConstructor
public class FeignClientInterceptor {

    private final JwtUtil jwtUtil;

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            // 从请求上下文中获取原始的 HttpServletRequest
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            // 从请求头中获取 JWT Token
            String token = jwtUtil.resolveReqToken(request);
            if (token != null) {
                // 将 JWT Token 添加到 Feign 请求头中
                template.header("Authorization", "Bearer " + token);
            }
        };
    }
}